import 'package:palmf_hid/common/apis/app.dart';
import 'package:palmf_hid/common/utils/my_log_util.dart';
import 'package:palmf_hid/common/utils/my_toast_util.dart';
import 'package:flutter_app_update/azhon_app_update.dart';
import 'package:flutter_app_update/update_model.dart';
import 'package:get/get.dart';

class UpdateHelper {
  static UpdateHelper? _instance;

  factory UpdateHelper() => getSingleton()!;

  UpdateHelper._internal();

  static UpdateHelper? getSingleton() {
    _instance ??= UpdateHelper._internal();
    return _instance;
  }

  ///检查更新
  void checkUpdate(String appVersion, bool showToast) {
    AppAPI.getUpdateInfo(showToast).then((value) {
      if (value != null) {
        if (value.versionCode == null || appVersion == "") {
          if (showToast) {
            MyToastUtil.show("alreadyTheLatestVersion".tr);
          }
          return;
        }
        int versionCodeWeb = int.parse(value.versionCode!);
        int versionCode = int.parse(appVersion);
        bool isForce = false;

        String url =
            "https://www.ihipro.net${value.downloadUrl!}${value.versionCode}.apk";

        if (value.isForce == 1) {
          isForce = true;
        }

        if (versionCodeWeb <= versionCode) {
          if (showToast) {
            MyToastUtil.show("alreadyTheLatestVersion".tr);
          }
          return;
        }
        UpdateModel model = UpdateModel(
            url, "flutterUpdate.apk", "ic_launcher", value.updateContent!,
            showNewerToast: true,
            apkVersionCode: versionCodeWeb,
            apkVersionName: value.versionName!,
            apkSize: value.apkSize!,
            iOSUrl: 'https://itunes.apple.com/cn/app/id6602885783',
            showiOSDialog: true,
            forcedUpgrade: isForce,
            showBgdToast: true,
            apkMD5: value.apkMd5!,
            showNotification: true);
        AzhonAppUpdate.update(model).then((value) => MyLogUtil().e("-"));
      }else{
        if (showToast) {
          MyToastUtil.show("alreadyTheLatestVersion".tr);
        }
      }
    });
  }
}
